'use client'

import { useState, useEffect, useCallback } from 'react'
import { useParams, useRouter } from 'next/navigation'
import {
    Card,
    Button,
    Tag,
    Spin,
    Alert,
    Image,
    Descriptions,
    Space,
    Divider
} from 'antd'
import {
    ArrowLeftOutlined,
    GlobalOutlined,
    DownloadOutlined,
    CalendarOutlined,
    LinkOutlined
} from '@ant-design/icons'
import { ProductDetailSkeleton } from '../../../components/LoadingSkeleton'
import { handleNetworkError, showSuccess } from '../../../utils/errorHandler'
import { formatDate } from '../../../utils/dateUtils'
import { validateProductData, formatProductForDisplay, getProductActions } from '../../../utils/productUtils'
import { downloadFile, generateDownloadFilename } from '../../../utils/downloadUtils'

export default function ProductDetailPage() {
    const params = useParams()
    const router = useRouter()
    const [product, setProduct] = useState(null)
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState(null)

    const productId = params.id

    // 获取产品详情
    const fetchProduct = useCallback(async (incrementView = false) => {
        try {
            setLoading(true)
            setError(null)

            console.log('正在获取产品详情，ID:', productId)
            const url = incrementView
                ? `/api/products/${productId}?increment_view=true`
                : `/api/products/${productId}`
            const response = await fetch(url)
            console.log('API响应状态:', response.status)

            if (!response.ok) {
                if (response.status === 404) {
                    throw new Error('产品不存在')
                }
                throw new Error(`HTTP error! status: ${response.status}`)
            }

            const data = await response.json()
            console.log('API响应数据:', data)

            if (data.success) {
                const productData = data.data.product || data.data
                console.log('解析的产品数据:', productData)

                // 验证产品数据的完整性
                if (!productData || typeof productData !== 'object') {
                    throw new Error('产品数据格式错误')
                }

                setProduct(productData)
            } else {
                throw new Error(data.error?.message || '获取产品详情失败')
            }
        } catch (err) {
            console.error('Error fetching product:', err)
            setError(err.message || '获取产品详情时发生错误')
            handleNetworkError(err)
        } finally {
            setLoading(false)
        }
    }, [productId])

    useEffect(() => {
        if (productId) {
            // 检查是否已经在本次会话中查看过这个产品
            const viewedProducts = JSON.parse(sessionStorage.getItem('viewedProducts') || '[]')
            const shouldIncrementView = !viewedProducts.includes(productId)

            if (shouldIncrementView) {
                // 记录已查看的产品
                viewedProducts.push(productId)
                sessionStorage.setItem('viewedProducts', JSON.stringify(viewedProducts))
            }

            fetchProduct(shouldIncrementView) // 只在首次查看时增加浏览量
        }
    }, [productId]) // 移除 fetchProduct 依赖，避免重复调用

    // 产品类型配置
    const typeConfig = {
        website: {
            label: '网站',
            color: 'blue',
            icon: <GlobalOutlined />,
            actionText: '访问网站',
            actionIcon: <GlobalOutlined />
        },
        app: {
            label: '应用',
            color: 'green',
            icon: <DownloadOutlined />,
            actionText: '下载应用',
            actionIcon: <DownloadOutlined />
        }
    }

    // 处理外部链接点击和文件下载
    const handleActionClick = async () => {
        if (product?.url) {
            if (product.type === 'website') {
                window.open(product.url, '_blank', 'noopener,noreferrer')
            } else if (product.type === 'app') {
                // 应用类型：触发文件下载
                let downloadUrl = product.url

                // 如果是本地文件路径，使用下载 API
                if (product.url.startsWith('/uploads/')) {
                    downloadUrl = `/api/download${product.url}`
                }

                const filename = generateDownloadFilename(product.title, product.url)

                try {
                    await downloadFile(downloadUrl, filename, {
                        onProgress: ({ status, progress }) => {
                            if (status === 'starting') {
                                showSuccess('开始下载', `正在准备下载 ${product.title}`)
                            }
                        },
                        onSuccess: ({ filename, size }) => {
                            showSuccess('下载完成', `${product.title} 下载成功`)
                        },
                        onError: (error) => {
                            console.error('下载失败:', error)
                            showSuccess('下载失败', error.message || '下载过程中发生错误')
                        }
                    })
                } catch (error) {
                    console.error('下载错误:', error)
                    showSuccess('下载失败', '无法启动下载，请稍后重试')
                }
            }
        }
    }

    // 返回列表
    const handleBack = () => {
        router.push('/products')
    }

    // 重试处理
    const handleRetry = () => {
        fetchProduct(false) // 重试时不增加浏览量
    }

    if (loading) {
        return (
            <div className="p-8">
                <ProductDetailSkeleton />
            </div>
        )
    }

    if (error) {
        return (
            <div className="p-8">
                <div className="max-w-4xl mx-auto">
                    <Button
                        icon={<ArrowLeftOutlined />}
                        onClick={handleBack}
                        className="mb-6"
                    >
                        返回列表
                    </Button>

                    <Alert
                        message="加载失败"
                        description={error}
                        type="error"
                        showIcon
                        action={
                            <Space>
                                <Button size="small" onClick={handleRetry}>
                                    重试
                                </Button>
                                <Button size="small" onClick={handleBack}>
                                    返回列表
                                </Button>
                            </Space>
                        }
                    />
                </div>
            </div>
        )
    }

    if (!product) {
        return (
            <div className="p-8">
                <div className="max-w-4xl mx-auto">
                    <Button
                        icon={<ArrowLeftOutlined />}
                        onClick={handleBack}
                        className="mb-6"
                    >
                        返回列表
                    </Button>

                    <Alert
                        message="产品不存在"
                        description="您访问的产品可能已被删除或不存在"
                        type="warning"
                        showIcon
                        action={
                            <Button size="small" onClick={handleBack}>
                                返回列表
                            </Button>
                        }
                    />
                </div>
            </div>
        )
    }

    const config = typeConfig[product?.type] || typeConfig.website

    return (
        <div className="p-8">
            <div className="max-w-4xl mx-auto">
                {/* 返回按钮 */}
                <Button
                    icon={<ArrowLeftOutlined />}
                    onClick={handleBack}
                    className="mb-6"
                >
                    返回列表
                </Button>

                {/* 产品详情卡片 */}
                <Card className="shadow-sm">
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                        {/* 左侧：图片 */}
                        <div>
                            <div className="relative">
                                <Image
                                    src={product?.thumbnail_url || '/placeholder-image.svg'}
                                    alt={product?.title || '产品图片'}
                                    className="w-full rounded-lg"
                                    fallback="/placeholder-image.svg"
                                />
                                {/* 产品类型标签 */}
                                <div className="absolute top-4 right-4">
                                    <Tag color={config.color} icon={config.icon} className="text-sm">
                                        {config.label}
                                    </Tag>
                                </div>
                            </div>
                        </div>

                        {/* 右侧：信息 */}
                        <div className="space-y-6">
                            {/* 标题和操作按钮 */}
                            <div>
                                <h1 className="text-3xl font-bold text-gray-900 mb-4">
                                    {product.title || '未命名产品'}
                                </h1>

                                <Space size="middle">
                                    <Button
                                        type="primary"
                                        size="large"
                                        icon={config.actionIcon}
                                        onClick={handleActionClick}
                                        disabled={!product?.url}
                                    >
                                        {config.actionText}
                                    </Button>

                                    {product?.url && (
                                        <Button
                                            icon={<LinkOutlined />}
                                            onClick={() => {
                                                navigator.clipboard.writeText(product.url)
                                                showSuccess('链接已复制', '链接已复制到剪贴板')
                                            }}
                                        >
                                            复制链接
                                        </Button>
                                    )}
                                </Space>
                            </div>

                            <Divider />

                            {/* 产品信息 */}
                            <Descriptions column={1} size="middle">
                                <Descriptions.Item label="产品类型">
                                    <Tag color={config.color} icon={config.icon}>
                                        {config.label}
                                    </Tag>
                                </Descriptions.Item>

                                {product?.url && (
                                    <Descriptions.Item label="访问地址">
                                        <a
                                            href={product.url}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="text-blue-600 hover:text-blue-800 break-all"
                                        >
                                            {product.url}
                                        </a>
                                    </Descriptions.Item>
                                )}

                                <Descriptions.Item label="创建时间">
                                    <Space>
                                        <CalendarOutlined />
                                        {formatDate(product?.created_at)}
                                    </Space>
                                </Descriptions.Item>
                            </Descriptions>

                            <Divider />

                            {/* 产品描述 */}
                            <div>
                                <h3 className="text-lg font-semibold text-gray-900 mb-3">
                                    产品描述
                                </h3>
                                <div className="text-gray-600 leading-relaxed whitespace-pre-wrap">
                                    {product?.description || '暂无描述'}
                                </div>
                            </div>
                        </div>
                    </div>
                </Card>
            </div>
        </div>
    )
}